package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.JSONUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class YanZhengActivity extends BaseActivity {
    //确认按钮
    private TextView zc_next;
    private TextView huo_qu_yan_zheng;
    private Timer timer;// 计时器
    private int jishi = 60;
    EditText shou_ji_hao, yan_zheng_ma;
    String tag;
    TextView xieyi;
    //协议
    private LinearLayout xieyi_linearlayout = null;
    //选择同意协议按钮
    private ImageView xieyi_imageview = null;
    //数据库
    private DBManager db = null;
    //记录是否同意协议
    private boolean lean = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhu_ce);
        db = new DBManager(this);
        zc_next = (TextView) findViewById(R.id.zc_next);
        TextView yan_zheng_title = (TextView) findViewById(R.id.yan_zheng_title);
        huo_qu_yan_zheng = (TextView) findViewById(R.id.huo_qu_yan_zheng);
        shou_ji_hao = (EditText) findViewById(R.id.shou_ji_hao);
        yan_zheng_ma = (EditText) findViewById(R.id.yan_zheng_ma);
        xieyi_imageview = (ImageView) findViewById(R.id.xieyi_imageview);
        xieyi_linearlayout = (LinearLayout) findViewById(R.id.xieyi_linearlayout);
        xieyi = (TextView) findViewById(R.id.xieyi);
        findViewById(R.id.xieyi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(YanZhengActivity.this, AgreementActivity.class));
            }
        });
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tag = getIntent().getStringExtra("tag");
        if (TextUtils.equals(tag, "0")) {
            yan_zheng_title.setText("注册账号");
            xieyi_linearlayout.setVisibility(LinearLayout.VISIBLE);
            xieyi.setText(Html.fromHtml("我已阅读并接受<font color='#fe7da6'><u>版权声明</u></font>和<font color='#fe7da6'><u>隐私条款</u></font>"));
        } else if (TextUtils.equals(tag, "1")) {
            yan_zheng_title.setText("修改密码");
            shou_ji_hao.setText(db.select("tel").replaceAll("(\\d{3})\\d{5}(\\d{3})", "$1*****$2"));
            shou_ji_hao.setFocusable(false);
            shou_ji_hao.setFocusableInTouchMode(false);
        } else if (TextUtils.equals(tag, "2")) {
            yan_zheng_title.setText("忘记密码");
        }
        //选择协议按钮
        xieyi_imageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lean) {
                    lean = false;
                    xieyi_imageview.setImageResource(R.mipmap.login_xieyi1);
                    zc_next.setBackgroundResource(R.drawable.button_gray_5);
                    zc_next.setTextColor(YanZhengActivity.this.getResources().getColor(R.color.black));
                    zc_next.setClickable(false);
                } else {
                    lean = true;
                    xieyi_imageview.setImageResource(R.mipmap.login_xieyi2);
                    zc_next.setBackgroundResource(R.drawable.button_red_5);
                    zc_next.setTextColor(YanZhengActivity.this.getResources().getColor(R.color.white));
                    zc_next.setClickable(true);
                }
            }
        });
        //提交
        zc_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                String sj = shou_ji_hao.getText().toString();
                String yzm = yan_zheng_ma.getText().toString();
                if (!TextUtils.isEmpty(sj) && !TextUtils.isEmpty(yzm)) {
                    yanZheng(sj, yzm);
                } else {
                    ToastUtil.showToast(YanZhengActivity.this, "手机号和验证码不能为空");
                }
            }
        });
        //获取验证码
        huo_qu_yan_zheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                String shou_ji = shou_ji_hao.getText().toString();
                if (TextUtils.isEmpty(shou_ji)) {
                    ToastUtil.showToast(YanZhengActivity.this, "手机号不能为空");
                } else {
                    huoQuYanZheng(shou_ji);
                }
            }
        });
    }

    AlertDialog yanzheng_dialog;

    //获取验证码
    private void yanZheng(final String sj, final String yzm) {
        yanzheng_dialog = new MyAlertDialog().ShowDialog(YanZhengActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String yz = null;
                    yz = Constants.getStringByName(YanZhengActivity.this, "YanZheng");
                    JSONObject jsonObject = new JSONObject(yz);
                    HashMap<String, String> param = new HashMap<>();
                    param.put("token", jsonObject.getString("token"));
                    param.put("account", sj);
                    param.put("code", yzm);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.YanZheng).put(formBody).build();
                    Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    //{"error":"invalid_grant","error_description":" 登录失败，用户名或密码错误！"}
                    if (code == 204) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    AlertDialog zhuce_dialog;

    //注册获取验证码
    private void huoQuYanZheng(final String shoujihao) {
        zhuce_dialog = new MyAlertDialog().ShowDialog(YanZhengActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HashMap<String, String> param = new HashMap<>();
                    if (TextUtils.equals(tag, "0")) {
                        param.put("function", "register");
                    } else if (TextUtils.equals(tag, "1")) {
                        param.put("function", "changepassword");
                    } else if (TextUtils.equals(tag, "2")) {
                        param.put("function", "forgetpassword");
                    }
                    param.put("mobile", shoujihao);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.HuoQuYanZhengMa).post(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    //{"error":"invalid_grant","error_description":" 登录失败，用户名或密码错误！"}
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler1.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler1.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg1 = new Message();
                    msg1.what = 1;
                    handler1.sendMessage(msg1);
                }
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler timerHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                huo_qu_yan_zheng.setEnabled(true);
                huo_qu_yan_zheng.setText("获取验证码");
                huo_qu_yan_zheng.setBackgroundResource(R.color.sys_fen);
                huo_qu_yan_zheng.setTextColor(YanZhengActivity.this.getResources().getColor(R.color.white));
                timer.cancel();
            } else {
                huo_qu_yan_zheng.setText(msg.what + "秒后重发");
            }
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    yanzheng_dialog.dismiss();
                    if (TextUtils.equals(tag, "0")) {
                        Intent intent = new Intent(YanZhengActivity.this, SheZhiMiMaActivity.class);
                        intent.putExtra("yanzheng", Constants.getStringByName(YanZhengActivity.this, "YanZheng"));
                        intent.putExtra("shoujihao", shou_ji_hao.getText().toString());
                        startActivity(intent);
                    } else if (TextUtils.equals(tag, "1")) {
                        Intent intent = new Intent(YanZhengActivity.this, ChongZhiMiMaActivity.class);
                        startActivity(intent);
                    } else if (TextUtils.equals(tag, "2")) {
                        Intent intent = new Intent(YanZhengActivity.this, WangJiMiMaActivity.class);
                        intent.putExtra("shoujihao", shou_ji_hao.getText().toString());
                        startActivity(intent);
                    }
                    finish();
                    break;
                case 1:
                    yanzheng_dialog.dismiss();
                    try {
                        JSONObject jsonObject = JSONUtil.strToJson(msg.obj.toString());
                        jsonObject = JSONUtil.strToJson(jsonObject.get("error").toString());
                        ToastUtil.showToast(YanZhengActivity.this, jsonObject.get("message").toString());
                    } catch (Exception e) {
                        ToastUtil.showToast(YanZhengActivity.this, "获取验证码失败，请稍后重新获取！");
                    }
                    break;
            }
        }
    };

    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    zhuce_dialog.dismiss();
                    Constants.setStringByName(YanZhengActivity.this, "YanZheng", msg.obj.toString());
                    jishi = 60;
                    huo_qu_yan_zheng.setEnabled(false);
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            timerHandler.sendEmptyMessage(jishi--);
                        }
                    }, 0, 1000);
                    huo_qu_yan_zheng.setBackgroundResource(R.color.gray);
                    huo_qu_yan_zheng.setTextColor(YanZhengActivity.this.getResources().getColor(R.color.black));
                    ToastUtil.showToast(YanZhengActivity.this, "验证码已发送到你的手机，请注意查收！");
                    break;
                case 1:
                    zhuce_dialog.dismiss();
                    // {"result":null,"targetUrl":null,"success":false,"error":{"code":0,"message":"验证码已过期，请重新获取","details":null,"validationErrors":null},"unAuthorizedRequest":false,"__abp":true}
                    try {
                        JSONObject jsonObject = JSONUtil.strToJson(msg.obj.toString());
                        jsonObject = JSONUtil.strToJson(jsonObject.get("error").toString());
                        ToastUtil.showToast(YanZhengActivity.this, jsonObject.get("message").toString());
                    } catch (Exception e) {
                        ToastUtil.showToast(YanZhengActivity.this, "获取验证码失败，请稍后重新获取！");
                    }
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }
}
